from Modules.sys_log.model import db, LogModel
from functools import wraps
from flask_login import current_user
from Common.BaseView import BaseView, Blueprint, Api, request
import json


# 系统日志
def system_log(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        account_id = None
        try:
            if account_id is None:
                if current_user.is_authenticated:
                    account_id = current_user.id
            res = func(*args, **kwargs)
            if account_id is None:
                if current_user.is_authenticated:
                    account_id = current_user.id

            if account_id is None:
                return res

            log_obj = {
                "req_module": request.path,
                "req_method": request.method,
                "req_hostIp": request.remote_addr,
                "req_data": '',
                "res_data": res.data
            }
            if log_obj['req_method'] == 'GET' or log_obj['req_method'] == 'DELETE':
                log_obj['req_data'] = request.query_string
            else:
                log_obj['req_data'] = json.dumps(request.json, ensure_ascii=False)

            log_ins = LogModel(account_id, log_obj)
            db.session.add(log_ins)
            db.session.commit()

            return res
        except Exception as error:
            print('日志装饰器错误：%s' % error)
    return decorated_view


logs_bp = Blueprint('logs', __name__, url_prefix='/api')
api = Api(logs_bp)


class LogsView(BaseView):
    def get(self):
        try:
            logs = self.to_array(current_user.logs)
            result_array = []
            for item in logs:
                result_array.append({
                    'id': item['id'],
                    'date': item['req_time'],
                    'module': item['req_module'],
                    'method': item['req_method'],
                    'ipaddr': item['req_hostIp'],
                    'reqdata': item['req_data'],
                    'resdata': item['res_data']
                })
            return self.result('0x00010', data=result_array)
        except Exception as error:
            print(error)
            return self.result('0x00011', data='%s' % error)

    def delete(self):
        try:
            pass
        except Exception as error:
            return self.result('0x00015', data='%s' % error)


api.add_resource(LogsView, '/logs')
